#include <QRegularExpression>
#include <QByteArray>

#include "peer_node_conn_socket.h"
#include "logger.h"

PeerNodeConnSocket::PeerNodeConnSocket(QObject *parent)
    :QTcpSocket(parent)
{
    connect(this,SIGNAL(readyRead()),this,SLOT(DataReceived()));
    connect(this,SIGNAL(disconnected()),this,SLOT(slotDisconnected()));
}

PeerNodeConnSocket::~PeerNodeConnSocket()
{

}

// 收到了客户端发送过来的  数据
void PeerNodeConnSocket::DataReceived()
{
    if(bytesAvailable() > 0)
    {
        char buf[1024];
        read(buf, 8); //先读取8个字节

        QString head = buf;
        long msglen = 0;
        QString kind;
        if(head == "error|||")
        {
            return;
        }
        else
        {
            // "NM0005hello" ==> kind="NM"  msglen=5, buf="hello",
            msglen = head.mid(2,6).toLong();
            kind = head.mid(0,2);
            read(buf,msglen);
            buf[msglen] = 0;
            MYLOG("recv header = %s, MsgKind = %s, msglen = %d",
                  head.toStdString().c_str(), kind.toStdString().c_str(), msglen);
        }

        //解析消息类型, 发射相关的信号, "NM0005hello" ==> kind="NM"  msglen=5, buf="hello",
        /////接受　新的客户端连接
        /////void Server::incomingConnection(int socketDescriptor) {}
        QString msg = buf;
        if(kind == "NM")
        {
            //name messsage
            QString logininfo = msg;
            emit UpdateUserName(logininfo);
        }
        else if(kind == "MM")
        {
            //meta message
            emit UpdateMeta(msg);
        }
        else if(kind == "SM")
        {
            //return share file message
            QString username = msg;
            emit ReturnMeta(username);
        }
        else if(kind == "DM")
        {
            //delete share file message
            emit DeleteMeta(msg);
        }
        else if(kind == "SR")
        {
            //search share file message
            emit SearchMeta(msg);
        }
        else if(kind == "DC")
        {
            //disconnected message
        }
        else if(kind == "GM")
        {
            //sign message
            emit UpdateUserInfo(msg);
        }
        else if(kind == "OT")
        {
            //normal message
            emit UpdateClients(msg, msg.length());
        }

    }
}
void PeerNodeConnSocket::slotDisconnected()
{
    emit Disconnected(this->socketDescriptor());
}
